﻿using System;
using System.Reflection;

using BizElements.BusinessLayer;

namespace BizElements.Web
{
    /// <summary>
    /// Nullable DateTime control property bound to a business object field (see: <see cref="IBindableField"/>).
    /// </summary>
    internal sealed class NullableDateTimePropertyBinder : IControlPropertyBinder
    {
        #region Contructors.

        /// <summary>
        /// Initializes a new instance of <b>NullableDateTimePropertyBinder</b> class.
        /// </summary>
        public NullableDateTimePropertyBinder()
        {
        }

        #endregion

        #region GetValue.

        /// <summary>
        /// Gets the value stored in the control.
        /// </summary>
        /// <param name="control">Control.</param>
        /// <param name="propertyName">Control property.</param>
        /// <param name="dataType">Ignored. Method always returns <b>DateTime?</b> value.</param>
        /// <param name="formatter">Not used.</param>
        /// <param name="errorCode">A value indicating the type of error encountered during parsing.</param>
        /// <returns>DateTime value stored in the control, or <b>null</b> if nothing is selected.</returns>
        public object GetValue(IBoundControl control, string propertyName, Type dataType, IMessageFormatter formatter, out ParseError errorCode)
        {
            // No parsing is taking place.
            errorCode = ParseError.AllOk;
            PropertyInfo controlProperty = control.GetType().GetProperty(propertyName);
            object val = controlProperty.GetValue(control, null);
            return val;
        }

        #endregion

        #region SetValue.

        /// <summary>
        /// Sets and display the given value.
        /// </summary>
        /// <param name="control">Control.</param>
        /// <param name="propertyName">Control property.</param>
        /// <param name="val">Null or a value convertible to <b>DateTime</b> type which is to be displayed by the control.</param>
        /// <param name="formatter">Not used.</param>
        public void SetValue(IBoundControl control, string propertyName, object val, IMessageFormatter formatter)
        {
            PropertyInfo property = control.GetType().GetProperty(propertyName);
            if (val != null)
                property.SetValue(control, Convert.ToDateTime(val), null);
            else
                property.SetValue(control, null, null);
        }

        #endregion
    }
}